package com.yanghui.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.yanghui.pojo.User;
import com.yanghui.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/admin")
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 显示当前用户详细信息
     */
    @RequestMapping("/showUser")
    public String showUser(HttpServletRequest request) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();

        request.setAttribute("id", user.getId());
        request.setAttribute("username", user.getUsername());
        request.setAttribute("email", user.getEmail());

        return "admin/user/basicInformation";
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public Map<String,Object> updateUser(User user) {
        Map<String,Object> map = new HashMap<>();
        int count = userService.updateUser(user);

        if (count == 1) {
            map.put("status", 200);
            map.put("message", "保存信息成功！");
        } else {
            map.put("status", 500);
            map.put("message", "保存信息失败！");
        }

        return map;
    }

    /**
     * 随机生成验证码
     * 验证码是保存在 Session 域中的，key 为 captcha
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /** 设置宽、高、位数 */
        CaptchaUtil.out(130, 48, 4, request, response);
    }

    /**
     * 刷新验证码，将验证码转换成 Base64 编码存到 Map 中
     * 验证码是保存在 Session 域中的，key 为 captcha
     */
    @RequestMapping("/refreshCaptcha")
    @ResponseBody
    public Map<String,Object> captcha2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> map = new HashMap<>();
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        map.put("image", specCaptcha.toBase64());
        return map;
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping("/login")
    public String toLogin() {
        return "/admin/login";
    }

    /**
     * 验证用户名和密码
     */
    @RequestMapping("/checkLogin")
//    @SystemLog(description = ConstantUtil.LOGIN_IN, userType = ConstantUtil.USER_TYPE_ADMIN)
    public String login(
            String username,
            String password,
            String captcha,
            HttpServletRequest request,
            HttpSession session,
            Model model) {
        String result = "";

        // System.out.println(request.getSession().getAttribute("captcha"));
        /** 判断验证码是否正确 */
        if (!CaptchaUtil.ver(captcha, request)) {
            /** 清除 Session 中的验证码 */
            CaptchaUtil.clear(request);

            model.addAttribute("status", 500);
            model.addAttribute("message", "验证码不正确！");
            return "admin/login";
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject currentUser = SecurityUtils.getSubject();

        try {
            if (!currentUser.isAuthenticated()) {
                /** 记住密码 */
                token.setRememberMe(true);
                /** 验证角色和权限 */
                currentUser.login(token);
            }
            model.addAttribute("status", 200);
            /** 验证成功，跳转到后台首页 */
            result = "admin/index2";
            /** 将用户名保存到 Session 域中 */
            session.setAttribute("username", username);
        } catch (Exception e) {
            /** 验证失败，跳转到登录页面 */
            result = "admin/login";
            model.addAttribute("status", 500);
            model.addAttribute("message", "用户名或密码错误");
        }

        return result;
    }

    /**
     * 退出
     */
    @RequestMapping("/logout")
//    @SystemLog(description = ConstantUtil.LOGIN_OUT, userType = ConstantUtil.USER_TYPE_ADMIN)
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        String result = "admin/login";
        /** 执行退出 */
        currentUser.logout();
        return result;
    }

}
